package cn.lcfms.app.admin.controller;

import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;

import cn.lcfms.bin.App;
import cn.lcfms.bin.Userinfo;
import cn.lcfms.service.BaseService;


public class BaseController {
    public static List<HashMap<String, Object>> itemcache=null;//用于缓存所有的栏目列表
    public static int firstitemid;
	/**
	 * 该方法将在执行控制器之前被执行
	 * @throws Exception 
	 */
    protected void beforeProtected(HttpServletRequest request,HttpServletResponse response) throws Exception{
    	if(itemcache==null){
    		set_item_cache();
    	}
    	if(firstitemid==0){
    		firstitemid=(int) App.APPCONFIG.get("firstitemid");
    	}
    }  
    /**
   	 * 该方法将在执行控制器之后，调入模板之前被执行
   	 */
    protected void afterProtected(HttpServletRequest request,HttpServletResponse response,ModelAndView view){  	
    	String contextPath = request.getContextPath();
	    String basePath = "";
	    if(request.getServerPort()==80){
	    	basePath = request.getScheme()+"://"+request.getServerName()+contextPath+"/";
	    }else{
	    	basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+contextPath+"/";
	    }	
	    request.setAttribute("APP", basePath); 
    	request.setAttribute("JS", basePath+"statics/ace/js/"); 
    	request.setAttribute("CSS", basePath+"statics/ace/css/"); 
    	request.setAttribute("IMG", basePath+"statics/ace/images/");   	
    	Userinfo.putUserInfo("firstitemid", firstitemid, request);
    	if(view!=null){
			String viewname=view.getViewName();		
			if(viewname.startsWith("local:")){
				view.setViewName("admin/local");
				view.addObject("LOCAL", viewname.substring(6));	
			}
		}
    }
    /**
	 * 初始化所有栏目
	 * @return
	 * @throws Exception
	 */
	private void set_item_cache() throws Exception {
		BaseService service = App.getService("item");
		List<HashMap<String, Object>> list=service.order("sort").selectList();
		for(int i=0;i<list.size();i++){
			long itemId=(long) list.get(i).get("itemId");
			for(int m=0;m<list.size();m++){
				int parentId=(int) list.get(m).get("parentId");
				if(parentId==itemId){
					list.get(i).put("hasChild", true);
					break;
				}
			}
		}		
		itemcache=list;	
	}
}
